import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/env/common_config.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_tab_icon.dart';

import 'package:casdon/common/widget/guide_overlay_widget.dart';
import 'package:casdon/common/widget/show_ad_dialog.dart';
import 'package:casdon/common/widget/update_dialog.dart';
import 'package:casdon/core/utils/shared_preferences_utils.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/device/application/notification/nfc_pairnet_controller.dart';

import 'package:casdon/modules/home/ui/screen/home_screen.dart';
import 'package:casdon/modules/lifeCircle/ui/screen/life_home_screen.dart';
import 'package:casdon/modules/me/application/notification/app_update_info_notifier.dart';
import 'package:casdon/modules/home/providers/home_provider.dart';

import 'package:casdon/modules/me/ui/screen/me_screen.dart';
import 'package:casdon/modules/recipe/ui/screen/recipe_home_screen.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';

@RoutePage()
class TabScreen extends ConsumerStatefulWidget {
  const TabScreen({super.key});

  @override
  ConsumerState<TabScreen> createState() => _TabScreenState();
}

class _TabScreenState extends ConsumerState<TabScreen>
    with WidgetsBindingObserver {
  late final PlatformTabController _tabController;
  int _currentIndex = 0;
  // 上次提醒时间，
  static const _optionalUpdatePromptKey = 'app_optional_update_prompt_at';
  static const _lastAdShownKey = 'home_ad_last_shown_at';

  static const Duration _optionalUpdateInterval = Duration(days: 7);
  String? _pendingUpdateContent;
  String _pendingUpdateType = '0';
  bool _isShowingUpdateDialog = false;
  bool _adChecked = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _tabController = PlatformTabController(initialIndex: 0);
    _tabController.addListener(() {
      setState(() {
        _currentIndex = _tabController.index(context);
      });
    });
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final controller = ref.read(nfcDeviceDiscoveryProvider.notifier);
      controller.initializeWithContext(context);
    });

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await _maybeShowAppUpdateDialog();
    });
  }

  @override
  void dispose() {
    Log.i("释放：TabScreen");
    _tabController.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  Future<void> _maybeShowPopupAd() async {
    final sp = await SPUtils.getInstance();
    final lastTs = sp.getInt(_lastAdShownKey, defValue: 0);
    final now = DateTime.now();
    final todayMidnight = DateTime(
      now.year,
      now.month,
      now.day,
    ).millisecondsSinceEpoch;
    // 如果今天已经弹出过，则返回
    if (lastTs >= todayMidnight) return;

    try {
      final list = await ref.read(popupListUsecaseProvider).execute();
      if (list == null || list.isEmpty) return;

      final item = list.first;
      if (!mounted) return;
      final ret = await showAdDialog(
        context: context,
        imageUrl: item.imageSrc,
        onImageTap: () => {
          WebPageRoute(url: item.linkUrl, title: '').push(context),
        },
      );
      if (ret != null && mounted) {
        await sp.setInt(_lastAdShownKey, now.millisecondsSinceEpoch);
      }
    } catch (e) {
      Log.w('弹出广告失败: $e');
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // 当从原生页面返回时，强制刷新 Flutter 页面
      setState(() {});
      // _showUpdateDialogIfNeeded();
    }
  }

  @override
  Widget build(BuildContext context) {
    ref.watch(nfcDeviceDiscoveryProvider);
    return GuideOverlayWidget(
      child: PlatformTabScaffold(
        tabController: _tabController,
        cupertino: (_, __) => CupertinoTabScaffoldData(),
        material: (_, __) => MaterialTabScaffoldData(),
        items: [
          BottomNavigationBarItem(
            icon: CommonTabIcon(
              normalIcon: Assets.images.tabHome.path,
              activeIcon: Assets.images.tabHomeSel.path,
              isActive: _currentIndex == 0,
            ),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: CommonTabIcon(
              normalIcon: Assets.images.tabItem1.path,
              activeIcon: Assets.images.tabItem1Sel.path,
              isActive: _currentIndex == 1,
            ),
            label: '菜谱',
          ),
          BottomNavigationBarItem(
            icon: CommonTabIcon(
              normalIcon: Assets.images.tabItem2.path,
              activeIcon: Assets.images.tabItem2Sel.path,
              isActive: _currentIndex == 2,
            ),
            label: '生活圈',
          ),
          BottomNavigationBarItem(
            icon: CommonTabIcon(
              normalIcon: Assets.images.tabItem4.path,
              activeIcon: Assets.images.tabItem4Sel.path,
              isActive: _currentIndex == 3,
            ),
            label: '我的',
          ),
        ],
        bodyBuilder: (context, index) {
          switch (index) {
            case 0:
              return HomeScreen();
            case 1:
              return RecipeHomeScreen();
            case 2:
              return LifeHomeScreen();
            case 3:
              return MeScreen();
            default:
              return SizedBox.shrink();
          }
        },
      ),
    );
  }

  Future<void> _maybeShowAppUpdateDialog() async {
    final upadateRet = await ref.read(appUpdateInfoProvider.future);
    if (!mounted) {
      return;
    }
    final info = upadateRet['data'] as Map<String, dynamic>?;
    if (info == null) {
      return;
    }
    final bool bUpdate = info['isUpdate'] as bool? ?? false;
    final versionInfo = info['versionInfo'] as Map<String, dynamic>?;
    if (!bUpdate || versionInfo == null) {
      return;
    }

    final updateType = versionInfo['updateType'] as String? ?? '0';

    _pendingUpdateContent = versionInfo['content'] as String? ?? '';
    _pendingUpdateType = updateType;
    if (versionInfo["verStr"] == null) return;
    final version = versionInfo["verStr"];
    final shouldShow = await _shouldShowUpdatePrompt(updateType, version);
    if (shouldShow) {
      await _showUpdateDialogIfNeeded(version);
    }
    // 更新检查结束后再尝试弹广告（仅执行一次）
    if (!_adChecked) {
      _adChecked = true;
      await _maybeShowPopupAd();
    }
  }

  Future<bool> _shouldShowUpdatePrompt(
    String updateType,
    String version,
  ) async {
    if (updateType == "2") {
      return true;
    }
    final sp = await SPUtils.getInstance();
    final donotAlert = sp.getBool(version);
    //当前更新版本已经设置了不再提醒
    if (donotAlert == true) {
      return false;
    }
    final lastPromptTs = sp.getInt(_optionalUpdatePromptKey, defValue: 0);
    final now = DateTime.now().millisecondsSinceEpoch;
    final allowShow =
        now - lastPromptTs >= _optionalUpdateInterval.inMilliseconds;
    if (allowShow) {
      await sp.setInt(_optionalUpdatePromptKey, now);
    }
    return allowShow;
  }

  Future<void> _openAppStore() async {
    final appUrl = CommonConfig.app_store_url;

    final uri = Uri.tryParse(appUrl);
    if (uri == null) {
      Log.w('无效的 App Store 链接: $appUrl');
      return;
    }

    final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
    if (!launched) {
      Log.w('无法打开 App Store 链接: $appUrl');
    }
  }

  Future<void> _showUpdateDialogIfNeeded(String version) async {
    if (!mounted ||
        _pendingUpdateContent == null ||
        _isShowingUpdateDialog == true) {
      return;
    }

    _isShowingUpdateDialog = true;
    final isForceUpdate = _pendingUpdateType == "2"; // 是否是强制更新
    final ret = await showUpdateDialog(
      isForceUpdate: isForceUpdate,
      context: context,
      title: "有新版本更新",
      cancelText: isForceUpdate ? "退出APP" : "取消",
      content: _pendingUpdateContent!,
      onConfirm: isForceUpdate ? _openAppStore : null,
      onDontRemindChanged: (skip) async {
        final sp = await SPUtils.getInstance();
        sp.setBool(version, skip);
      },
    );

    _isShowingUpdateDialog = false;

    if (!mounted) {
      return;
    }

    if (ret == null) {
      // 对话框被系统关闭（如切到后台），保持待展示状态，前台时再尝试弹出
      return;
    }

    _pendingUpdateContent = null;

    if (ret) {
      await _openAppStore();
    } else if (isForceUpdate) {
      Log.d("用户选择退出app，拒绝更新");
      exit(0);
    }
  }
}
